package com.itheima.service;

import com.itheima.common.R;
import com.itheima.domain.Address;
import com.itheima.mapper1.AddressMapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.DeleteMapping;

import java.util.List;

/**
 * @author wuyiqiang
 * @2022/6/19 15:31
 */
@Service
public class AddressService {
    @Autowired
    private AddressMapper addressMapper;

    /**
     * 获取默认收货地址
     *
     * @return
     */
    public Address getAddress() {
        return addressMapper.getAddress();
    }

    /**
     * 设置默认地址
     *
     * @param id
     * @return
     */
    public Address setAddress(String id) {
        //获取默认收货地址的对象
        Address address = addressMapper.getAddress();

        //判断设置的默认地址的id是否就是原来的默认地址id
        if (address.getId().equals(id)) {
            return address;
        } else {
            address.setIsDefault(0);
            addressMapper.setAddress(address);
            //获取该id对应的对象
            Address address1 = addressMapper.selectById(id);
            address1.setIsDefault(1);
            addressMapper.setAddress(address1);
            return address1;
        }
    }

    /**
     * 查询地址列表
     *
     * @return
     */
    public List<Address> selectAll() {
        return addressMapper.selectAll();
    }

    /**
     * 根据id查询信息
     *
     * @param id
     * @return
     */
    public Address selectById(String id) {
        Address address = addressMapper.selectById(id);
        return address;
    }

    /**
     * 新增收货地址
     *
     * @param address
     */
    public void add(Address address) {

        //将时间戳作为id
        address.setId(System.currentTimeMillis() + "");
        addressMapper.add(address);
    }

    /**
     * 删除收货地址
     * @param ids
     */
    public R delete(String ids) {
        Address address = addressMapper.selectById(ids);
        int isDefault = address.getIsDefault();
        if (isDefault==1){
            return R.error("是默认地址不能删除");
        }
        addressMapper.delete(ids);
        return R.success(" ");
    }

    /**
     * 修改收货地址
     * @param address
     */
    public void update(Address address) {
        addressMapper.update(address);
    }
}
